﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using Alexim.Model;



namespace Alexim.DAL
{
    public class BecaDAL
    {


        public delegate T ReaderHandler<T>(IDataReader reader);

        public List<Beca> getBecaInformation(int idCarrera, int idTipoestudio)
        {
            string ConnectionString = @"Data Source=LAP_U02728\SQLEXPRESS; Database=becas_db;User ID=sa;password=upcsa2013";
            List<SqlParameter> par = getParametersBecaInformation(idCarrera, idTipoestudio);
            return this.ExecuteReaderWithList<Beca>(ConnectionString, CommandType.StoredProcedure, "UP_GETBECA", ObtenerDatoDeReaderSelectAll, par.ToArray());

        }

        private Beca ObtenerDatoDeReaderSelectAll(IDataReader ir)
        {
            Beca entity = new Beca();

            entity.Carrera = ir.GetString(0);
            entity.Universidad = ir.GetString(1);
            entity.FechaInicio = ir.GetDateTime(2);

            return entity;
        }



        public List<SqlParameter> getParametersBecaInformation(int idCarrera, int idTipoestudio)
        {
            List<SqlParameter> par = new List<SqlParameter>();
            par.Add(new SqlParameter("@CARRERA", SqlDbType.Int, 4));
            par[0].Value = idCarrera;

            par.Add(new SqlParameter("@TIPOESTUDIO", SqlDbType.Int, 4));
            par[1].Value = idTipoestudio;


            return par;
        }


        ////////////////////////////////////////////////////////////////////////////////////
        public  System.Collections.Generic.List<T> ExecuteReaderWithList<T>(string connectionString, CommandType cmdType, string cmdText, ReaderHandler<T> handler, params SqlParameter[] commandParameters)
        {
            System.Collections.Generic.List<T> l = new System.Collections.Generic.List<T>();
            using (SqlDataReader rdr = ExecuteReader(connectionString, cmdType, cmdText, commandParameters))
            {
                while (rdr.Read())
                {
                    T value = handler(rdr);
                    l.Add(value);
                }
                return l;
            }
        }

        /// <summary>
        /// Prepare a command for execution
        /// </summary>
        /// <param name="cmd">SqlCommand object</param>
        /// <param name="conn">SqlConnection object</param>
        /// <param name="trans">SqlTransaction object</param>
        /// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
        /// <param name="cmdText">Command text, e.g. Select * from Products</param>
        /// <param name="cmdParms">SqlParameters to use in the command</param>
        private  void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {

            if (conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;

            if (trans != null)
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;

            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }



        /// <summary>
        /// Execute a SqlCommand that returns a resultset against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>A SqlDataReader containing the results</returns>
        public  SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);

            // we use a try/catch here because if the method throws an exception we want to 
            // close the connection throw code, because no datareader will exist, hence the 
            // commandBehaviour.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch
            {
                conn.Close();
                throw;
            }
        }

    }
}
